package pers.kw.message.server.service;

import com.alibaba.fastjson.JSONObject;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import pers.kw.contants.RabbitMQContants;
import pers.kw.message.dto.znx.ZnxReqDto;
import pers.kw.message.server.persist.entity.MessageZnxDO;

import javax.annotation.Resource;
import java.util.List;

/**
 * 站内信消费者监听
 */
@Slf4j
@Component
public class MQZnxListener {

    @Resource
    private MessageService messageService;

    @RabbitListener(queues = {RabbitMQContants.ZNX_QUEUE})
    public void consume(String msg, Channel channel, Message message)
            throws Exception {
        //根据applyId，查询记录，防止重复消费
        ZnxReqDto reqDto = JSONObject.parseObject(msg, ZnxReqDto.class);
        List<MessageZnxDO> list = messageService.listZnxByApplyId(reqDto.getApplyId());
        if (CollectionUtils.isEmpty(list)) {
            log.info("站内信消费成功：{}", msg);
            // 手动ACK
            messageService.addZnx(reqDto);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } else {
            //消息已被消费，丢弃消息
            log.info("站内信消息已被消费，请勿重复投递：{}", msg);
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), false);
        }
    }
}
